//
//  M1LoginVC.m
//  NewMarryU
//
//  Created by apple on 2018/7/12.
//  Copyright © 2018年 Cedar. All rights reserved.
//

#import "M1LoginVC.h"
#import "M1LoginView.h"
#import "M1RealNameViewController.h"
#import <AdSupport/AdSupport.h>
#import "M1_DES.h"
#import "M1LoginJump.h"
#import "M1UserAgreeVC.h"
@interface M1LoginVC ()
@property (nonatomic ,strong) M1LoginView *m1_phoneView;
@property (nonatomic ,strong) M1LoginView *m1_codeView;
@property (nonatomic ,strong) UIButton *m1_loginBtn;
@property (nonatomic ,strong) UIButton *m1_codeBtn;
@end

@implementation M1LoginVC
-(UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleLightContent;
}

-(void)m1_loginBtnClick{
    WEAKSELF;
    NSDictionary *m1_params = @{@"country_code":@(86),
                                @"phone":[_m1_phoneView.m1_TF.text m1_removeWhitespace],
                                @"code":[_m1_codeView.m1_TF.text m1_removeWhitespace]};
    [M1HttpNet requestWithMethod:m1_phone_login_url params:m1_params success:^(id resDic, NSInteger code, NSString *message) {
        
        [M1User save:resDic];
        M1User *user = [M1User mj_objectWithKeyValues:resDic];
        
        [M1User saveModel:user];
        [weakSelf m1_loginEaseIM];
        [M1LoginJump m1_loginWith:user vc:weakSelf];
        
    } fail:^(id resDic, NSInteger code, NSString *message) {
        [M1Alert m1_alertWithTitle:nil message:message];
    } showAni:YES];
}

-(void)m1_loginEaseIM{
    WEAKSELF;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        EMError *error = [[EMClient sharedClient] loginWithUsername:[[M1User user].basic.uid m1_MD5] password:[M1User user].token];
        dispatch_async(dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
            if (!error) {
                [[EMClient sharedClient].options setIsAutoLogin:YES];
                [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_LOGINCHANGE object:[NSNumber numberWithBool:YES]];
            } else {
                [M1Alert m1_alertWithTitle:nil message:@"聊天登录失败"];
            }
        });
    });
}


-(void)m1_getCode{
    
    if (_m1_phoneView.m1_TF.text.length != 11) {
        [M1Alert m1_alertWithTitle:nil message:@"手机号码输入不正确，请更改"];
        return;
    }
    
    NSString *m1_ifa = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
    NSString *m1_conv_time = [NSString stringWithFormat:@"%.0f",[[NSDate date] timeIntervalSince1970]];
    NSString *m1_encrypt_key = [M1SaveTool m1_appConfig].encrypt_key;
    NSString *m1_sign_key = [M1SaveTool m1_appConfig].sign_key;
    
    NSString *m1_sign_string = [NSString stringWithFormat:@"sign_key=%@&country_code=%@&phone=%@&conv_time=%@&ifa=%@",m1_sign_key,@(86),_m1_phoneView.m1_TF.text,m1_conv_time,m1_ifa];
    
    NSString * m1_string = [[M1_DES m1_md5EncodingStr:m1_sign_string] lowercaseString];
    
    NSString *m1_query_string = [NSString stringWithFormat:@"%@&sign=%@",m1_sign_string,m1_string];
    NSString *m1_sign = [self m1_stringForEnWith:m1_query_string key:m1_encrypt_key];
    NSDictionary *params = @{@"country_code":@(86),
                             @"phone":_m1_phoneView.m1_TF.text,
                             @"conv_time":m1_conv_time,
                             @"ifa":m1_ifa,
                             @"sign":[[m1_sign dataUsingEncoding:NSUTF8StringEncoding] base64EncodedStringWithOptions:0]
                             };
    WEAKSELF;
    [M1HttpNet requestWithMethod:m1_get_sms_url params:params success:^(id resDic, NSInteger code, NSString *message) {
        [M1Alert m1_alertWithTitle:nil message:@"验证码发送成功"];
        m1_CountDownTime(60, 1, ^(NSTimeInterval time) {
            [weakSelf.m1_codeBtn setTitle:[NSString stringWithFormat:@"%ds",(int)time] forState:0];
        }, ^{
            [weakSelf.m1_codeBtn setTitle:@"重新获取验证码" forState:0];
        });
    } fail:^(id resDic, NSInteger code, NSString *message) {
        [M1Alert m1_alertWithTitle:nil message:message];
    } showAni:YES];
}

void m1_CountDownTime(NSTimeInterval timeOut,NSTimeInterval timeInterval,void(^runningHandler)(NSTimeInterval time),void(^stopHandler)(void)){
    __block NSTimeInterval m1_time = timeOut+timeInterval;
    __block NSTimeInterval timeinterval = timeInterval;
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t m1_timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    dispatch_source_set_timer(m1_timer, dispatch_walltime(NULL, 0), timeInterval * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
    dispatch_source_set_event_handler(m1_timer, ^{
        if (m1_time <= timeinterval) {
            dispatch_source_cancel(m1_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                stopHandler();
            });
        }else{
            m1_time -=timeinterval;
            dispatch_async(dispatch_get_main_queue(), ^{
                runningHandler(m1_time);
            });
        }
    });
    dispatch_resume(m1_timer);
}

-(NSString *)m1_stringForEnWith:(NSString *)string key:(NSString *)key{
    NSData* m1_bytes = [string dataUsingEncoding:NSUTF8StringEncoding];
    Byte  *m1_myByte = (Byte *)[m1_bytes bytes];
    NSData* m1_keyBytes = [key dataUsingEncoding:NSUTF8StringEncoding];
    Byte  *m1_keyByte = (Byte *)[m1_keyBytes bytes];
    for (NSInteger i = 0; i < [m1_bytes length]; i++)
    {
        NSInteger j = i % [m1_keyBytes length];
        m1_myByte[i] = m1_myByte[i]^m1_keyByte[j];
    }
    NSData *m1_Data = [[NSData alloc] initWithBytes:m1_myByte length:[m1_bytes length]];
    NSString *m1_String = [[NSString alloc] initWithData:m1_Data encoding:NSUTF8StringEncoding];
    return m1_String;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationItem.title = @"登录";
    
    
    UIImageView *m1_bgView = [[UIImageView alloc]init];
    m1_bgView.image  =[UIImage imageNamed:@"regist_bg"];
    m1_bgView.clipsToBounds = YES;
    m1_bgView.contentMode = UIViewContentModeScaleAspectFill;
    [self.view addSubview:m1_bgView];
    [m1_bgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_offset(UIEdgeInsetsMake(0, 0, 0, 0));
    }];
    _m1_phoneView = [[M1LoginView alloc]init];
    _m1_phoneView.layer.cornerRadius = 27.5;
    _m1_phoneView.m1_TF.placeholder = @"手机号";
    _m1_phoneView.m1_TF.tag = 1;
    _m1_phoneView.m1_TF.clearButtonMode = UITextFieldViewModeWhileEditing;
    [_m1_phoneView.m1_TF addTarget:self action:@selector(m1_tfChaged:) forControlEvents:UIControlEventAllEditingEvents];
    _m1_phoneView.m1_imgView.image = [UIImage imageNamed:@"login_phone"];
    [self.view addSubview:_m1_phoneView];
    
    [_m1_phoneView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(20);
        make.right.offset(-20);
        make.height.mas_offset(55);
        make.top.offset(SCREENHEIGHT*0.52-(iPhone4?40:0));
    }];
    
    _m1_codeView = [[M1LoginView alloc]init];
    _m1_codeView.layer.cornerRadius = 27.5;
    _m1_codeView.m1_TF.placeholder = @"验证码";
    _m1_codeView.m1_TF.tag = 2;
    [_m1_codeView.m1_TF addTarget:self action:@selector(m1_tfChaged:) forControlEvents:UIControlEventAllEditingEvents];
    _m1_codeView.m1_imgView.image = [UIImage imageNamed:@"login_pw"];
    [self.view addSubview:_m1_codeView];
    
    [_m1_codeView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(20);
        make.right.offset(-20);
        make.height.mas_offset(55);
        make.top.equalTo(_m1_phoneView.mas_bottom).offset(20);
    }];
    
    _m1_codeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_m1_codeBtn setTitle:@"获取验证码" forState:0];
    _m1_codeBtn.titleLabel.font = m1_font(15);
    
    [_m1_codeBtn addTarget:self action:@selector(m1_getCode) forControlEvents:UIControlEventTouchUpInside];
    [_m1_codeView addSubview:_m1_codeBtn];
    [_m1_codeBtn setTitleColor:[UIColor m1_colorHex:0x999999] forState:0];
    _m1_codeBtn.userInteractionEnabled = NO;
    [_m1_codeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.equalTo(_m1_codeView.mas_height);
        make.right.offset(-25);
        make.centerY.equalTo(_m1_codeView.mas_centerY);
    }];
    

    _m1_loginBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_m1_loginBtn setTitle:@"登录" forState:0];
    [_m1_loginBtn setTitleColor:[UIColor whiteColor] forState:0];
    _m1_loginBtn.titleLabel.font = m1_font(16);
    _m1_loginBtn.layer.cornerRadius = 27.5;
    _m1_loginBtn.clipsToBounds = YES;
    _m1_loginBtn.userInteractionEnabled = NO;
    [_m1_loginBtn addTarget:self action:@selector(m1_loginBtnClick) forControlEvents:UIControlEventTouchUpInside];
    _m1_loginBtn.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.4];
    [self.view addSubview:_m1_loginBtn];
    
    [_m1_loginBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(20);
        make.right.offset(-20);
        make.height.mas_offset(55);
        make.top.equalTo(_m1_codeView.mas_bottom).offset(20);
    }];
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setTitleColor:[UIColor m1_colorHex:0x999999] forState:0];
    btn.titleLabel.font = m1_font(10);
    WEAKSELF;
    [btn m1_handler:^(UIButton *sender) {
        [weakSelf.navigationController pushViewController:[M1UserAgreeVC new] animated:YES];
    }];
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc]initWithString:@"进入默认您同意 《MarryU用户服务协议》"];
    [str addAttributes:@{NSForegroundColorAttributeName:[UIColor m1_colorHex:0x999999]} range:NSMakeRange(0, 7)];
    [str addAttributes:@{NSForegroundColorAttributeName:[UIColor m1_colorHex:0x999999],NSUnderlineStyleAttributeName:@(NSUnderlinePatternSolid | NSUnderlineStyleSingle),NSStrikethroughColorAttributeName:[UIColor m1_colorHex:0x999999],NSFontAttributeName:m1_font(12)} range:NSMakeRange(8, 14)];
    [btn setAttributedTitle:str forState:0];
    [self.view addSubview:btn];
    [btn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.top.equalTo(_m1_loginBtn.mas_bottom).offset(15);
    }];
}
-(void)m1_tfChaged:(UITextField *)tf{
    if (tf.tag == 1) {
        if (tf.text.length >11) {
            tf.text = [tf.text substringWithRange:NSMakeRange(0, 11)];
        }
        
        if (tf.text.length >=8) {
            [_m1_codeBtn setTitleColor:[UIColor m1_colorHex:0xFF5A3F] forState:0];
            _m1_codeBtn.userInteractionEnabled = YES;
        }else{
            [_m1_codeBtn setTitleColor:[UIColor m1_colorHex:0x999999] forState:0];
            _m1_codeBtn.userInteractionEnabled = NO;
        }
    }else{
        if (tf.text.length >6) {
            tf.text = [tf.text substringWithRange:NSMakeRange(0, 6)];
        }
    }
    
    if (_m1_phoneView.m1_TF.text.length >=8 && _m1_codeView.m1_TF.text.length >=4) {
        [_m1_loginBtn setBackgroundImage:[UIImage imageNamed:@"btn_color"] forState:0];
        _m1_loginBtn.userInteractionEnabled = YES;
    }else{
        [_m1_loginBtn setBackgroundImage:[UIImage new] forState:0];
        _m1_loginBtn.userInteractionEnabled = NO;
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
